import React, { Component } from 'react'
import GoodsCar from '../../components/GoodsCar';
import Header from '../../components/Header'
import Search from '../../components/Search';
import {reqGetcate, reqGetgoods} from '../../http/api'
import './Cate.less'


export default class Cate extends Component {
  constructor(){
    super();
    this.state = {
      cateArr:[],
      cateGoodsArr:[],
      isActive:0
    }
  }
  componentDidMount(){
    // 获取分类数据
    this.getCateInfo(reqGetcate,'cateArr').then((id)=>{
      // 获取分类商品
      this.getCateInfo(reqGetgoods, 'cateGoodsArr', {fid:id})
    })
    
  }
  async getCateInfo(fn, key, params={}){
    try {
      let res;
      if(Object.keys(params).length>0){
        res = await fn(params);
      }else{
        res = await fn();
      }
      
      if(res.data.code===200){
        this.setState({
          [key]:res.data.list
        })
        return res.data.list[0].id 
      }
    }catch(err){
      console.log(err);
    }
  }
  async getCateGoods(e,id,index){
    // 修改isActive,改变侧边栏选中
    this.state.isActive = index;
    // 获取相应的cateGoods数据
    this.getCateInfo(reqGetgoods, 'cateGoodsArr', {fid:id})
    
  }
  render() {
    let {cateArr,cateGoodsArr,isActive} = this.state;
    return (
      <div className='Cate'>
          <Header title="商品分类" back></Header>
          <Search></Search>
          <div className="main">
            <div className="left">
              {cateArr.map((item,index)=>{
                return <div className={index===isActive?'item active':'item'} onClick={(e)=>{this.getCateGoods(e,item.id,index)}} key={item.id}>
                  {item.catename}
                </div>
              })}
            </div>
            <div className="right">
              <GoodsCar goodsArr={cateGoodsArr}></GoodsCar>
            </div>
          </div>
      </div>
    )
  }
}
